#include "stdio.h"
#include "stdlib.h"
#include "string.h"

#include "sys/ipc.h"
#include "sys/shm.h"
#include <stdio.h>
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "unistd.h"
#include "errno.h"
#include "cJSON.h"

#define serv_PORT 8888
#define serv_IP "192.168.112.207"

int main()
{
    int servfd = -1;
    struct sockaddr_in servaddr;
    int ret = 0;
    int datafd = -1;
    char buf[100] = "";

    servfd = socket(AF_INET,SOCK_STREAM,0);

    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(serv_PORT);
    inet_aton(serv_IP,&servaddr.sin_addr);

    ret = bind(servfd,(struct sockaddr*)&servaddr,sizeof(servaddr));

    ret += listen(servfd,9);

    if(ret)
    {
	printf("in server,bind or listen failed\n");
	close(servfd);
	servfd = -1;
	return 1;
    }

    int shm_id;
    shm_id = shmget(0x300,100,IPC_CREAT|0777);
    if(shm_id < 0)
    {
	perror("shmget");
	return -1;
    }

    printf("共享内存创建成功!\n");

    char* string =  shmat(shm_id,NULL,0);
    
    while(1)
    {
	datafd = accept(servfd,NULL,NULL);
	if(datafd < 0)
	{
	    if(errno == EINTR)
	    {
		continue;
	    }
	    else
	    {
		printf("accept failed\n");
		break;
	    }
	}
	else
	{   
	    read(datafd,buf,100);
	    strcpy(string,buf);
	    printf("%s\n",string);
	    close(datafd);
	}
    }

    close(servfd);
    servfd = -1;
    return 0;
}


